<template>
  <div class="app-container">
    <el-form ref="temp" :model="temp" :rules="rules" class="form-container">
      <el-form-item prop="title">
        <el-input v-model="temp.title" :maxlength="100" name="title" required placeholder="标题">
          <template slot="append">
            <span class="word-counter">{{ contentShortLength }}/100</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="content">
        <Tinymce ref="editor" v-model="temp.content" :height="600" url="/blog/article/upload" />
      </el-form-item>
      <el-form-item prop="tag" label="文章标签：">
        <el-tag
          :key="tag"
          v-for="tag in temp.tags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >{{tag}}</el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="mini"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="mini" @click="showInput">+</el-button>
        <div>
          <el-checkbox-group v-model="temp.tags" :max="3">
            <el-checkbox @change="handleTag" v-for="tag in tags" :label="tag" :key="tag">{{tag}}</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="success" plain @click="handlePublished">保存并发布</el-button>
        <el-button type="danger" plain @click="handleDraft">保存草稿</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  saveArticleInfo,
  getArticleInfo,
  getArticleTags,
  saveArticleTagInfo,
  deleteArticleTag
} from "@/api/blog/article";
import MDinput from "@/components/MDinput";
import Tinymce from "@/components/Tinymce";
export default {
  components: { MDinput, Tinymce },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    var validateTitle = function(rule, value, callbock) {
      if (value === "" || value === undefined) {
        callbock(new Error("标题不能为空"));
      } else if (value.length > 100) {
        callbock(new Error("标题长度为100位字符"));
      } else {
        callbock();
      }
    };
    return {
      tags: [],
      inputVisible: false,
      inputValue: "",
      temp: {
        id: undefined,
        title: "",
        content: "",
        status: "",
        tags: []
      },
      rules: {
        title: [{ required: true, validator: validateTitle }]
      },
      tempRoute: {}
    };
  },
  created() {
    this.getTags();
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id;
      this.getInfo(id);
    }
  },
  computed: {
    contentShortLength() {
      return this.temp.title.length;
    }
  },
  methods: {
    getInfo(id) {
      getArticleInfo(id).then(response => {
        this.temp = response.data;
      });
    },
    getTags() {
      getArticleTags().then(response => {
        this.tags = response.data;
      });
    },
    handleClose(tag) {
      this.temp.tags.splice(this.temp.tags.indexOf(tag), 1);
      deleteArticleTag(tag).then(response => {
        if (response.success) {
          this.tags.splice(this.tags.indexOf(tag), 1);
        }
      });
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    setPageTitle() {
      const title = "编辑文章";
      document.title = `${title}-${this.temp.id}`;
    },
    setTagsViewTitle() {
      const title = "编辑文章";
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.temp.id}`
      });
      this.$store.dispatch("tagsView/updateVisitedView", route);
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        saveArticleTagInfo(inputValue).then(response => {
          if (response.success) {
            this.tags.push(inputValue);
            if (this.temp.tags.length < 3) {
              this.temp.tags.push(inputValue);
            }
          } else this.$message({ message: response.message, type: "error" });
        });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    handleTag(row) {},
    handlePublished() {
      this.temp.status = "Published";
      this.saveData();
    },
    handleDraft() {
      this.temp.status = "Draft";
      this.saveData();
    },
    saveData() {
      if (this.temp.content === "") {
        this.$message({ message: "内容不能为空", type: "error" });
        return false;
      }
      this.$refs.temp.validate(valid => {
        if (valid) {
          const loading = this.$loading({ text: "正在保存数据" });
          saveArticleInfo(this.temp)
            .then(response => {
              this.temp.id = response.data;
              loading.close();
              this.$message({
                message: response.message,
                type: response.success ? "success" : "error"
              });
            })
            .catch(err => {
              console.error(err);
              loading.close();
            });
        }
      });
    }
  }
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>